{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:58:51.904493Z",
     "start_time": "2025-01-08T15:58:51.900757Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "id": "b07e44f0acaf7be2",
   "outputs": [],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "groupby() 方法用于对数据进行分组，并对每个分组应用聚合、转换或过滤操作，适用于对数据进行分组统计。\n",
    "\n",
    "df.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, dropna=True)\n",
    "\n",
    "相关参数：\n",
    "\n",
    "by：用于分组的列名、函数、字典或 Series。\n",
    "\n",
    "axis：分组方向，axis=0（默认）表示按行分组，axis=1 表示按列分组。\n",
    "\n",
    "as_index：是否将分组列作为索引，默认为 True。\n",
    "\n",
    "sort：是否对分组键进行排序，默认为 True。\n",
    "\n",
    "dropna：是否忽略 NaN 值，默认为 True"
   ],
   "id": "16fbfbfd06ed148b"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 一些常用方法",
   "id": "a2ecdb378ca049ce"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:40.376487Z",
     "start_time": "2025-01-08T15:05:40.371545Z"
    }
   },
   "source": [
    "# 创建 DataFrame\n",
    "data = {\n",
    "    'Group': ['A', 'A', 'B', 'B', 'C', 'C'],\n",
    "    'Value': [1, 2, 3, 4, 5, 6]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Group  Value\n",
      "0     A      1\n",
      "1     A      2\n",
      "2     B      3\n",
      "3     B      4\n",
      "4     C      5\n",
      "5     C      6\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:40.381553Z",
     "start_time": "2025-01-08T15:05:40.377488Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 按 'Group' 列分组\n",
    "grouped = df.groupby(by='Group')\n",
    "print(grouped)"
   ],
   "id": "c49089afdb6829e8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000022D276D8980>\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:40.389517Z",
     "start_time": "2025-01-08T15:05:40.382553Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算每组的均值\n",
    "print(grouped.mean())"
   ],
   "id": "c1ac4ded84cbc7bc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       Value\n",
      "Group       \n",
      "A        1.5\n",
      "B        3.5\n",
      "C        5.5\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:40.411410Z",
     "start_time": "2025-01-08T15:05:40.404480Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算每组的均值和总和\n",
    "print(grouped.agg(['mean', 'sum']))"
   ],
   "id": "3cf021b1ce1eb7bf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      Value    \n",
      "       mean sum\n",
      "Group          \n",
      "A       1.5   3\n",
      "B       3.5   7\n",
      "C       5.5  11\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:40.421607Z",
     "start_time": "2025-01-08T15:05:40.412411Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算每组的标准化值\n",
    "df['ZScore'] = grouped['Value'].transform(lambda x: (x - x.mean()) / x.std())\n",
    "print(df)"
   ],
   "id": "392b4dba36314be5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Group  Value    ZScore\n",
      "0     A      1 -0.707107\n",
      "1     A      2  0.707107\n",
      "2     B      3 -0.707107\n",
      "3     B      4  0.707107\n",
      "4     C      5 -0.707107\n",
      "5     C      6  0.707107\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:05:42.183778Z",
     "start_time": "2025-01-08T15:05:42.177497Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 过滤出均值大于 3 的组\n",
    "filtered = grouped.filter(lambda x: x['Value'].mean() > 3)\n",
    "print(filtered)"
   ],
   "id": "270e3cf8b0774086",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Group  Value    ZScore\n",
      "2     B      3 -0.707107\n",
      "3     B      4  0.707107\n",
      "4     C      5 -0.707107\n",
      "5     C      6  0.707107\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 多列分组",
   "id": "c2c7550314daa0b8"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:09:19.927656Z",
     "start_time": "2025-01-08T15:09:19.922104Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 创建 DataFrame\n",
    "data = {\n",
    "    'Group1': ['A', 'A', 'B', 'B', 'C', 'C'],\n",
    "    'Group2': ['X', 'Y', 'X', 'Y', 'X', 'Y'],\n",
    "    'Value': [1, 2, 3, 4, 5, 6]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ],
   "id": "6a57a9d591f33775",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Group1 Group2  Value\n",
      "0      A      X      1\n",
      "1      A      Y      2\n",
      "2      B      X      3\n",
      "3      B      Y      4\n",
      "4      C      X      5\n",
      "5      C      Y      6\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T15:09:52.226082Z",
     "start_time": "2025-01-08T15:09:52.220610Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 按 'Group1' 和 'Group2' 列分组\n",
    "grouped = df.groupby(['Group1', 'Group2'])\n",
    "# 计算每组的均值\n",
    "print(grouped.mean())"
   ],
   "id": "ad3ae2c25a963cd7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "               Value\n",
      "Group1 Group2       \n",
      "A      X         1.0\n",
      "       Y         2.0\n",
      "B      X         3.0\n",
      "       Y         4.0\n",
      "C      X         5.0\n",
      "       Y         6.0\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "方法\t            描述\n",
    "\n",
    "sum()\t        计算每组的和。\n",
    "\n",
    "mean()\t        计算每组的均值。\n",
    "\n",
    "max()\t        计算每组的最大值。\n",
    "\n",
    "min()\t        计算每组的最小值。\n",
    "\n",
    "count()\t        计算每组的非空值数量。\n",
    "\n",
    "size()\t        计算每组的大小（行数）。\n",
    "\n",
    "agg()\t        对每组应用一个或多个聚合函数。\n",
    "\n",
    "transform()\t    对每组应用转换函数，返回相同形状的结果。\n",
    "\n",
    "filter()\t    根据条件过滤分组。\n",
    "\n",
    "apply()\t        对每组应用自定义函数。"
   ],
   "id": "10ba80b47a7c624b"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
